package com.gao.flying.mq.util;

import com.gao.flying.mq.config.Broker;
import com.gao.flying.mq.config.Config;
import com.gao.flying.mq.config.Dest;
import com.gao.flying.mq.config.Scan;
import org.apache.commons.digester3.Digester;
import org.apache.commons.digester3.annotations.FromAnnotationsRuleModule;
import org.apache.commons.digester3.binder.DigesterLoader;

import static org.apache.commons.digester3.binder.DigesterLoader.newLoader;

/**
 * @author gaojh
 * @date 2016/7/12
 */
public class XmlUtils {

    private static Config config = null;


    public static Config getConfig() {
        if (config == null) {
            DigesterLoader loader = newLoader(new FromAnnotationsRuleModule() {
                @Override
                protected void configureRules() {
                    bindRulesFrom(Config.class);
                }

            });

            Digester digester = loader.newDigester();
            try {
                config = digester.parse(Thread.currentThread().getContextClassLoader().getResourceAsStream("config/jms.xml"));

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        return config;
    }

    public static Broker getBroker(String name) {
        Config config = getConfig();
        for (Broker broker : config.getBrokers()) {
            if (broker.getName().equals(name)) {
                return broker;
            }
        }
        return null;
    }


    public static Dest getDestination(String name) {
        Config config = getConfig();
        for (Dest dest : config.getDests()) {
            if (dest.getName().equals(name)) {
                return dest;
            }
        }
        return null;
    }


    public static Scan getScan() {
        Config config = getConfig();
        return config.getScan();
    }

}
